package com.atguigu.flinksql;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Expressions;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.table.api.TumbleWithSizeOnTimeWithAlias;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.expressions.Expression;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

public class Flink11_Window_Grouped {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        DataStream<WaterSensor> waterSensorStream =
                env
                        .fromElements(new WaterSensor("sensor_1", 1001L, 10),
                                new WaterSensor("sensor_1", 2000L, 20),
                                new WaterSensor("sensor_1", 4001L, 40),
                                new WaterSensor("sensor_1", 5000L, 50),
                                new WaterSensor("sensor_2", 3000L, 30),
                                new WaterSensor("sensor_2", 6000L, 60))
                        .assignTimestampsAndWatermarks(
                                WatermarkStrategy
                                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                        .withTimestampAssigner((ws, ts) -> ws.getTs())
                        );

        //1、创建表环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        //2、根据流创建表
        Table table = tEnv.fromDataStream(waterSensorStream, $("id"), $("ts").rowtime(), $("vc"));
        //3、创建一个滚动窗口
        TumbleWithSizeOnTimeWithAlias w = Tumble
                .over(Expressions.lit(5).second())
                //设置那个字段作为时间
                .on($("ts"))
                //给窗口起一个别名
                .as("w");

        table.window(w)
                //这里是得到全量数据，我们需要分组获取各个窗口之间得数据
                //根据用户id和窗口分组，相当于keyBy和window
                .groupBy($("id"),$("w"))
                .select($("id"),$("w").start().as("windowStart"),$("w").end().as("windowEnd"),$("vc").sum().as("vc_sum"))
                .execute().print();


    }
}
